package ge.telasi.tasks.ui.comp;

import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;

/**
 * Table model based on a list.
 *
 * @author dimitri
 */
public abstract class TableModel<T> extends DefaultTableModel {
    protected List<T> data;

    public T getObjectAt(int index) {
        try {
            return data.get(index);
        } catch (IndexOutOfBoundsException ex) {
            return null;
        }
    }

    public List<T> getObjectsAt(int[] indecies) {
        List<T> list = new ArrayList<T>();
        for (int index : indecies) {
            T object = data.get(index);
            if (object != null) {
                list.add(object);
            }
        }
        return list;
    }

    @Override
    public int getRowCount() {
        return data == null ? 0 : data.size();
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
        fireTableDataChanged();
    }

    public boolean addItem(T item) {
        if (data == null) {
            data = new ArrayList<T>();
        }
        if (data.add(item)) {
            fireTableDataChanged();
            return true;
        }
        return false;
    }

    public boolean removeItem(T item) {
        if (data != null) {
            if (data.remove(item)) {
                fireTableDataChanged();
                return true;
            }
        }
        return false;
    }

    public boolean replaceItemAt(T item, int index) {
        if(data.set(index, item) != null) {
            fireTableDataChanged();
            return true;
        }
        return false;
    }

    public int indexOf (T item) {
        return data.indexOf(item);
    }

    public boolean addItemAtHead(T item) {
        if (data == null) {
            data = new ArrayList<T>();
        }
        data.add(0, item);
        fireTableDataChanged();
        return true;
    }

    public boolean setItemAt(int index, T item) {
        T removed = data.set(index, item);
        fireTableDataChanged();
        return removed != null;
    }


    public boolean addItemAt(int index, T item) {
        data.add(index, item);
        fireTableDataChanged();
        return true;
    }

}
